<template>
  <div class="person-container flex-column">
    <Breadcrumb>
      <template #bread-name>
        个性错题本-{{ studentInfo.studentName }}
      </template>
      <template #bread-right>
        <div class="select-box flex">
          <el-select
            v-model="search.stageOption"
            style="width: 120px"
            :disabled="true"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-date-picker
            v-model="search.timeRange"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :disabled-date="disabledDate"
            @change="onChangeTime"
          />
        </div>
      </template>
    </Breadcrumb>
    <main class="person-content flex">
      <ul class="person-left flex-column">
        <div class="tab-list flex">
          <div
            @click="onChangeTab(tab.value)"
            :class="[
              'tab-item',
              'hover',
              tab.value === activeTab && 'tab-item-active'
            ]"
            v-for="(tab, index) in tabList"
            :key="index"
          >
            {{ tab.label }}
          </div>
        </div>
        <div class="left-content">
          <template v-if="activeTab === '0'">
            <el-empty
              v-if="!taskList.length"
              v-loading="leftLoading"
            ></el-empty>
            <li
              class="task-item flex-between"
              :class="index === activeTaskIndex && 'task-item-active'"
              @click="onSelectTask(index)"
              v-for="(task, index) in taskList"
              :key="index"
            >
              <span :title="task.name" class="task-name text-ellipsis hover">{{
                task.name
              }}</span>
              <span>{{ task.count }}道</span>
            </li>
          </template>
          <template v-else>
            <el-tree
              ref="treeRef"
              :data="treeData"
              style="max-width: 100%"
              @node-click="onNodeClick"
              node-key="id"
              highlight-current
              :default-checked-keys="activeKnow"
            >
              <template #default="{ data }">
                <div class="topic-title text-ellipsis" :title="data.name">
                  {{ data.name }}&nbsp;({{ data.count }})道
                </div>
              </template>
            </el-tree>
          </template>
        </div>
      </ul>
      <div class="person-right">
        <div class="select-tool flex">
          <el-select
            v-model="questionType"
            placeholder="请选择题型"
            style="width: 240px"
            clearable
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="2"
            multiple
          >
            <el-option
              v-for="item in questionTypeOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-select style="width: 120px" v-model="correctType">
            <el-option
              v-for="item in correctOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div class="desc">
          共找到符合条件错题： <span class="text">{{ pageInfo.total }}</span
          >道 &nbsp;&nbsp;&nbsp;&nbsp; 本页共
          <span class="text">{{ questionList.length }}</span>
          道题目 &nbsp;&nbsp;&nbsp;
          <el-button
            text
            type="primary"
            @click="onAddBasket"
            :disabled="!questionList.length"
            >本页全选</el-button
          >
        </div>
        <el-empty v-if="!questionList.length" v-loading="rightLoading" />
        <AssignTopic
          v-for="(question, index) in questionList"
          :key="index"
          :index="index + 1"
          :topic-data="question.question"
        />

        <el-pagination
          v-if="pageInfo.total"
          class="flex-end"
          layout="prev, pager, next"
          :total="pageInfo.total"
          v-model:current-page="pageInfo.pageIndex"
          @change="getWrongTargetInfo"
        />
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, watchEffect, reactive, watch, computed } from 'vue'
import { useRoute } from 'vue-router'
import { useAuthStore, useTaskStore } from '@/stores'
import { storeToRefs } from 'pinia'
import {
  getQuestionCount,
  getQuestionType,
  getWrongTarget,
  getTaskCount
} from '@/apis/assignment/index'
import { subjectMap, gradeMap } from '@/constants/subject-map'
import Breadcrumb from '@/components/Breadcrumb.vue'
import dayjs from 'dayjs'
import AssignTopic from '../components/AssignTopic.vue'
import { debounce } from '@/utils/debounce'

const route = useRoute()
const { nowGlobalStageId, nowGlobalSubjectId } = storeToRefs(useAuthStore())
const taskStore = useTaskStore()
const leftLoading = ref(false)
const rightLoading = ref(false)

const tabList = ref([
  {
    value: '0',
    label: '练习任务列表'
  },
  {
    value: '1',
    label: '知识图谱'
  }
])
const activeTab = ref(tabList.value[0].value)
const options = computed(() => [
  {
    value: '1',
    label: `${gradeMap[nowGlobalStageId.value]}${subjectMap[nowGlobalSubjectId.value]}`
  }
])
const search = reactive({
  stageOption: options.value[0].value,
  timeRange: []
})
const studentInfo = ref({
  studentId: '',
  studentName: '',
  classId: '',
  classType: '',
  gradeNum: 0
})
const questionTypeOption = ref([]) // 题型选项
const questionType = ref([])

const correctOption = [
  {
    value: '0',
    label: '全部'
  },
  {
    value: '2',
    label: '已订正'
  },
  {
    value: '1',
    label: '未订正'
  }
]
const correctType = ref('0') // 重练状态
const questionList = ref([])
const pageInfo = ref({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 获取题型
const getQuestionTypeInfo = async () => {
  const res = await getQuestionType({
    subject_id: nowGlobalSubjectId.value,
    stage_id: nowGlobalStageId.value
  })
  questionTypeOption.value = res.data.map(item => ({
    value: item.data.id,
    label: item.data.name
  }))
}

// ----------------------任务练习列表
const taskList = ref([])
const activeTaskIndex = ref(null)
const onSelectTask = index => {
  resetData()
  activeTaskIndex.value = index
}
/**
 * 获取练习任务列表
 */
const getTaskCountInfo = async () => {
  if (activeTab.value !== '0') return
  if (!studentInfo.value.studentId) return
  leftLoading.value = true
  const res = await getTaskCount({
    class_id: studentInfo.value.classId,
    class_type: studentInfo.value.classType,
    start_time: search.timeRange?.length
      ? dayjs(search.timeRange[0]).startOf('day').unix()
      : null,
    end_time: search.timeRange?.length
      ? dayjs(search.timeRange[1]).endOf('day').unix()
      : null,
    student_id: studentInfo.value.studentId,
    subject_id: nowGlobalSubjectId.value
  })
  leftLoading.value = false
  taskList.value = res.data.data
  if (taskList.value.length) {
    activeTaskIndex.value = 0
  }
}

// ----------------------知识图谱板块
const activeKnow = ref([])
const treeData = ref([])
const treeRef = ref()

const getIds = (tree, result) => {
  for (let i = 0; i < tree.length; i++) {
    result.push(tree[i].id)
    if (tree[i].children) {
      getIds(tree[i].children, result)
    }
  }
  return result
}

const onNodeClick = param => {
  resetData()
  activeKnow.value = getIds([param], [])
}
/**
 * 获取树状结构
 */
const getQuestionCountInfo = async () => {
  if (activeTab.value !== '1') return
  if (!studentInfo.value.studentId) return
  leftLoading.value = true
  const res = await getQuestionCount({
    grade_id: studentInfo.value.gradeNum,
    class_type: studentInfo.value.classType,
    class_id: studentInfo.value.classId,
    subject_id: nowGlobalSubjectId.value,
    student_id: studentInfo.value.studentId,
    start_time: search.timeRange.length
      ? dayjs(search.timeRange[0]).startOf('day').unix()
      : null,
    end_time: search.timeRange.length
      ? dayjs(search.timeRange[1]).endOf('day').unix()
      : null
  })
  leftLoading.value = false
  treeData.value = res.data?.data || []
  activeKnow.value = getIds(treeData.value, [])
}

/**
 * 题目列表
 */
const getWrongTargetInfo = async () => {
  if (!studentInfo.value.studentId) return
  pageInfo.value.total = 0
  questionList.value = []
  rightLoading.value = true
  const res = await getWrongTarget({
    class_id: studentInfo.value.classId,
    class_type: studentInfo.value.classType,
    student_id: [studentInfo.value.studentId],
    subject_id: nowGlobalSubjectId.value,
    category: questionType.value,
    order_by: 1,
    start_time: search.timeRange.length
      ? dayjs(search.timeRange[0]).startOf('day').unix()
      : null,
    end_time: search.timeRange.length
      ? dayjs(search.timeRange[1]).endOf('day').unix()
      : null,
    page: pageInfo.value.pageIndex,
    size: pageInfo.value.pageSize,
    knowledge_ids:
      activeTab.value === '1' && activeKnow.value ? activeKnow.value : [],
    grasp: Number(correctType.value),
    task_id:
      activeTab.value === '0' && activeTaskIndex.value != null
        ? [taskList.value[activeTaskIndex.value].id]
        : []
  })
  rightLoading.value = false
  questionList.value = res.data.data || []
  pageInfo.value.total = res.data.total
}

const resetData = () => {
  pageInfo.value = {
    pageIndex: 1,
    pageSize: 10,
    total: 0
  }
  questionList.value = []
  activeTaskIndex.value = null
  activeKnow.value = []
}

const onChangeTab = v => {
  console.log(1212212, v)

  activeTab.value = v
  resetData()
}

// 左侧列表
watchEffect(() => {
  resetData()
  if (activeTab.value === '0') {
    getTaskCountInfo()
  } else {
    getQuestionCountInfo()
  }
})

// 右侧题目列表
watch(
  [questionType, activeKnow, correctType, activeTaskIndex],
  () => {
    debounce(() => {
      getWrongTargetInfo()
    }, 200)
  },
  {
    deep: true
  }
)

watch(
  [nowGlobalStageId, nowGlobalSubjectId],
  () => {
    getQuestionTypeInfo()
  },
  {
    deep: true,
    immediate: true
  }
)

// 题目数据加入选题篮中
const onAddBasket = () => {
  let list = questionList.value.map(item => ({
    topic_id: item.question.id,
    topic_type: item.question.type,
    is_similar: 0,
    relation_id: 0,
    question_detail: item.question,
    source: item.question.source,
    subject_id: item.question.subject
  }))
  taskStore.setTaskList(list, true)
}

const disabledDate = time => {
  return time.getTime() > Date.now()
}

const onChangeTime = param => {
  if (!param) {
    initData()
  }
}

const initData = () => {
  studentInfo.value = {
    studentId: route.query.studentId,
    studentName: route.query.studentName,
    classId: route.query.classId,
    classType: Number(route.query.classType),
    gradeNum: Number(route.query.gradeNum)
  }
  search.timeRange = [
    route.query.startTime || null,
    route.query.endTime || null
  ]
}

initData()
</script>

<style lang="less" scoped>
.person-container {
  height: calc(100vh - 60px);
  overflow: hidden;
  .select-box {
    gap: 20px;
  }
  .person-content {
    margin-top: 20px;
    gap: 20px;
    align-items: self-start;
    overflow: hidden;
    flex: 1;
    .person-left {
      height: 100%;
      width: 400px;
      background-color: #fff;
      padding: 10px 10px 10px 20px;
      box-sizing: border-box;
      gap: 20px;
      .tab-list {
        gap: 30px;
        .tab-item {
          color: #72757e;
        }
        .tab-item-active {
          color: #333333;
          font-weight: bold;
          font-size: 18px;
        }
      }
      .task-item {
        margin-bottom: 4px;
        line-height: 2.6;
        padding: 0 10px;
        border-radius: 10px;
        &:hover {
          background-color: #f7f9ff;
          color: #1a70e8;
          cursor: pointer;
        }
        .task-name {
          max-width: 80%;
        }
      }
      .task-item-active {
        background-color: #f7f9ff;
        color: #1a70e8;
      }
      .left-content {
        flex: 1;
        overflow-y: auto;
        :deep(.el-tree-node__content) {
          height: unset;
        }
        :deep(
            .el-tree--highlight-current
              .el-tree-node.is-current
              > .el-tree-node__content
          ) {
          background-color: #f7f9ff;
          color: #1a70e8;
        }
        .topic-title {
          width: 80%;
          font-size: 16px;
          line-height: 2.6 !important;
          color: #000;
        }
      }
    }
    .person-right {
      max-height: calc(100vh - 110px);
      box-sizing: border-box;

      padding: 20px;
      flex: 1;
      background-color: #fff;
      overflow-y: auto;
      .select-tool {
        gap: 20px;
      }
      .desc {
        margin: 20px 0;
        .text {
          color: @theme-color;
        }
      }
    }
  }
}
</style>
